package api

import (
	"encoding/base64"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gcache"
	"go-middle/app/admin/service/loginservice"
	"go-middle/app/common/model/admin"
	"go-middle/app/common/model/admin_online"
	"go-middle/library/captcha"
	"go-middle/library/response"
	"go-middle/library/token"
)

// Login   密码登录
// @Tags    登录
// @Summary 账号密码登录
// @Accept  multipart/form-data
// @Produce  json
// @Param   username formData string true  "用户名或手机号"
// @Param   password formData string true  "密码"
// @Param   captcha formData string true  "图形验证码"
// @Success 200 {object} response.JsonResponse "code 0成功1失败"
// @Router /api/login [post]
// @Security ApiKeyAuth
func Login(r *ghttp.Request) {
	var req loginservice.ReqLoginAccount
	// 获取参数
	if err := r.Parse(&req); err != nil {
		response.Error(r, err.Error(), nil)
	}
	// 图形验证
	if !captcha.Verify(req.Captcha, r.Session.Id()) {
		response.Error(r, "图形验证码错误", nil)
	}
	gcache.Remove(r.Session.Id() + loginservice.CaptchaKey)
	if loginservice.CheckLock(req.UserName) {
		response.Error(r, "账号已锁定", nil)
	}
	user, err := loginservice.SignIn(req.UserName, req.Password)
	if err != nil {
		e := loginservice.SetPasswordCounts(req.UserName)
		response.Error(r, err.Error()+e, nil)
	} else {
		// 移除登陆次数记录
		loginservice.RemovePasswordCounts(req.UserName)
		// 更新token
		tokens, err := token.Generate(user.User)
		if err != nil {
			response.Error(r, "内部错误", nil)
			return
		}
		_ = r.Session.RemoveAll()
		r.Session = tokens.Session
		_ = r.Session.Set("uid", user.Id)
		_ = r.Session.Set("user", user.User)
		_ = r.Session.Set(loginservice.AdminInfo, user)
		// 设置在线
		loginservice.SetOnLine(r)
		respUser := &admin.RespUserInfo{}
		_ = r.Session.GetStruct(loginservice.AdminInfo, respUser)
		response.Success(r, "登录成功", g.Map{
			"token": r.Session.Id(),
			"user":  respUser,
		})
	}
}

// Captcha  图形验证码
// @Tags    登录
// @Summary 图形验证码
// @Accept  multipart/form-data
// @Produce  html
// @Success 200 {string} string "验证码图形"
// @Router /api/captcha [get]
// @Security ApiKeyAuth
func Captcha(r *ghttp.Request) {
	b64s, _ := captcha.Generate(captcha.Math, r.Session.Id())
	b, _ := base64.RawStdEncoding.DecodeString(b64s[22:])
	r.Response.Header().Set("Content-Type", "image/png")
	r.Response.WriteExit(b)
}

// Logout  退出登录
// @Tags    登录
// @Summary 退出登录
// @Accept  multipart/form-data
// @Produce  json
// @Success 200 {object} response.JsonResponse
// @Router /api/logout [post]
// @Security ApiKeyAuth
func Logout(r *ghttp.Request) {
	_, _ = admin_online.Model.Where("token=?", r.Session.Id()).Delete()
	_ = token.SessionStore.RemoveAll(r.Session.Id())
	r.Cookie.Remove(r.Cookie.GetSessionId())
	response.Success(r, "退出成功", nil)
}
